import { platform } from '@/util/platform'
import { h5Auth } from '@/model/authToLogin/h5Auth'
import { appAuth } from '@/model/authToLogin/appAuth'
import { navigate } from '@/util/navigate'
import { env } from '@/config/config'
import store from '@/store/store'

async function auth() {
  return
  // #ifdef H5
  const authException = sessionStorage.getItem('authException')
  if (authException === 'true') {
    console.log('已经授权，不进行授权')
    return
  } else {
    console.log('未授权')
  }
  // #endif

  try {
    let objToken
    const { programState } = store
    const previousTime = uni.getStorageSync('authTime')
    const presentTime = new Date().getTime()
    if (presentTime - +previousTime < 6000) return
    uni.setStorageSync('authTime', presentTime)

    // #ifdef MP-WEIXIN
    objToken = await appAuth()
    // #endif
    // #ifdef H5
    objToken = await h5Auth()
    // #endif
    // if (platform === 'MP-WEIXIN') {
    //   objToken = await appAuth()
    // } else if (programState.browser.wx) {
    //   objToken = await h5Auth()
    // }
    return objToken
  } catch (error) {}
}
// #ifdef H5
async function gotoLogin() {
  const userToken = JSON.parse(uni.getStorageSync('userToken_zh_web') || '{}')
  if (!userToken.token) {
    const url = `${window.location.href}`
    const authException = sessionStorage.getItem('authException')
    if (authException !== 'true' && !url.includes('code=')) {
      // 旧的跳转逻辑
      // uni.setStorageSync("redirectUri", url);
      // setTimeout(() => navigate({ url: "/pages/login/index" }), 1000);
      //
      uni.setStorageSync('redirectUri', url)
      await auth()
      return false
    }
  }
  return true
}
// #endif


// #ifdef MP-WEIXIN
async function gotoLogin() {
  const userToken = JSON.parse(uni.getStorageSync('userToken_zh_web') || '{}')
  console.log(Boolean(!userToken.token))
  if (!userToken.token) {
    await auth()
    console.log('微信授权登录')
  }
}
// #endif

export { auth, gotoLogin }
